<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\index\controller;
use think\Db;
use think\View;
class Addshop extends Base
{
    /**
     * 报备
     */
    public function index()
    {
//        $userInfo = Db::table('up_u_user')->where('user_id',session('user_id'))->find();
//        $oldData = Db::table('up_shop_copy')
//            ->where('s_u_userid',$userInfo['user_id'])
//            ->find();
//        $this->assign('oldData',$oldData);
        return $this->fetch();
    }

    /**
     * 提交报备信息
     * @return \think\response\Json
     */
    public function commitShop(){
        extract(input());

        if(!$addressDetail) return json(['status' => 0, 'msg' => '请填写详细地址']);
        if(!$areaid) return json(['status' => 0, 'msg' => '请选择所在地区']);
        if(!$lonlat) return json(['status' => 0, 'msg' => '请选择地点']);
        if(!$s_inside_name) return json(['status' => 0, 'msg' => '请输入老师名称']);
        if(!$s_inside_phone) return json(['status' => 0, 'msg' => '请输入老师电话']);
        if(!$s_com_name) return json(['status' => 0, 'msg' => '请输入店名']);
        if(!$s_name) return json(['status' => 0, 'msg' => '请输入联系人']);
        if(!$s_phone) return json(['status' => 0, 'msg' => '请输入联系电话']);
        if(!$s_content) return json(['status' => 0, 'msg' => '请输入沟通要点']);

        if(mb_strlen($s_content) < 50){
            return json(['status'=>0,'msg'=>'沟通要点字数不能少于50字']);
        }
        //----------------------------手机相关的验证 start -----------------------------------
        if(!preg_match("/^1[23456789]\d{9}$/", $s_inside_phone)){
            return json(['status'=>0,'msg'=>'请填写正确的老师手机号']);
        }
        if(!preg_match("/^1[23456789]\d{9}$/", $s_phone)){
            return json(['status'=>0,'msg'=>'请填写正确的联系电话']);
        }
        if($s_phone == $s_inside_phone){
            return json(['status'=>0,'msg'=>'老师手机号不能与联系电话一样']);
        }
        if($s_phone1){
            if(!preg_match("/^1[23456789]\d{9}$/", $s_phone1)){
                return json(['status'=>0,'msg'=>'请填写正确的联系电话2']);
            }
            if($s_phone1 == $s_inside_phone){
                return json(['status'=>0,'msg'=>'老师电话不能与联系电话2一样']);
            }
        }
        if($s_phone2){
            if(!preg_match("/^1[23456789]\d{9}$/", $s_phone2)){
                return json(['status'=>0,'msg'=>'请填写正确的联系电话3']);
            }
            if($s_phone2 == $s_inside_phone){
                return json(['status'=>0,'msg'=>'老师电话不能与联系电话3一样']);
            }
        }
        //手机号有没有人提交
        $have = $this->forPhoneThree($s_phone, $s_phone1, $s_phone2);
        if($have){
            return json(['status'=>0,'msg'=>'此手机号已经有人提交']);
        }

        $area = explode('-',$areaid);
        $lalo = explode(',',$lonlat);
        $mile = Db::table('up_about')->where('id', 11)->value('content');
        $miles = (int)$mile;
        $lat = $lalo[0];
        $lon = $lalo[1];
        $field = 's_id, s_com_name';
        $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - s_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(s_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - s_lon * PI() / 180) / 2),2))) * 1000) AS distance';
        $is_apply = Db::table('up_shop')
            ->field($field)
            ->where(['s_status' => 2, 's_protect' => 1])
            ->having("distance <= $miles")
            ->find();

        if($is_apply){
            return json(['status' => 0, 'msg' => '保护范围内已经有加盟的商家了！']);
//            return json(['status' => 0, 'msg' => $is_apply]);
        }else{
            $haveNumber = Db::table('up_shop')->field($field)->having("distance <= $miles")->select();
//            return json(['status' => 0, 'msg' => $haveNumber]);
            if(count($haveNumber) >= 5) return json(['status' => 0, 'msg' => '该保护范围内，已有5家加盟商']);
        }

        $userInfo = Db::table('up_u_user')->where('user_id', session('user_id'))->find();
        $config = Db::table('up_shop_config')->where('id', 1)->find();
        $data = [
            's_u_name' => $userInfo['user_username'],
            's_u_phone' => $userInfo['user_phone'],
            's_u_userid' => $userInfo['user_id'],
            's_com_name' => $s_com_name,
            's_name' => $s_name,
            's_phone' => $s_phone,
            's_phone1' => $s_phone1,
            's_phone2' => $s_phone2,
            's_time' => date('Y-m-d H:i:s'),
            's_endtime' => date('Y-m-d H:i:s',time()+(3600*24*20)),
            's_update_time' => date('Y-m-d H:i:s'),
            's_inside_name' => $s_inside_name,
            's_inside_phone' => $s_inside_phone,
            's_address' => $addressDetail,
            's_sheng' => $area[0],
            's_shi' => $area[1],
            's_qu' => $area[2],
            's_area_str' => $address,
            's_lon' => $lalo[1],
            's_lat' => $lalo[0],
            's_days' => $config['default']
        ];
        $insert_img = [
            'si_u_name' => $userInfo['user_username'],
            'si_u_phone' => $userInfo['user_phone'],
            'si_u_userid' => $userInfo['user_id'],
            'si_name' => $s_name,
            'si_phone' => $s_phone,
            'si_wechat' => $s_wx_name,
            'si_content' => $s_content,
            'si_remark' => $s_remark,
            'si_images' => $upload,
            'si_days' => $config['default'],
            'si_time' => date('Y-m-d H:i:s'),
            'si_update_time' => date('Y-m-d H:i:s')
        ];

        Db::startTrans();
        try{
            //手机号有没有人提交
            $have = $this->forPhoneShop($s_phone,$s_phone1,$s_phone2);
            if($have){
                $insert_img['si_s_id'] = $have;
                Db::table('up_shop')->where('s_id',$have)->update($data);
            }else{
                $sid = Db::table('up_shop')->insertGetId($data);
                $insert_img['si_s_id'] = $sid;
            }
            Db::table('up_shop_image')->insertGetId($insert_img);

            Db::commit();
            return json(['status' => 200, 'msg' => '提交成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }

    }

    /**
     * 报备第一步
     */
    public function firstStep()
    {
        extract(input());
        $userInfo = Db::table('up_u_user')->where('user_id',session('user_id'))->find();
        $config = Db::table('up_shop_config')->where('id',1)->find();

        $insert = [
            's_u_name' => $userInfo['user_username'] ,
            's_u_phone' => $userInfo['user_phone'] ,
            's_u_userid' => $userInfo['user_id'] ,
            's_com_name' => $s_com_name ,
            's_name' => $s_name ,
            's_phone' => $s_phone ,
            's_phone1' => $s_phone1 ,
            's_phone2' => $s_phone2 ,
            's_time' => date('Y-m-d H:i:s') ,
            's_endtime' => date('Y-m-d H:i:s',time()+(3600*24*20)) ,
            's_update_time' => date('Y-m-d H:i:s') ,
            's_verify' => 1 ,
            's_status' => 1 ,
            's_inside_name' => $s_inside_name ,
            's_inside_phone' => $s_inside_phone ,
            's_days' => $config['default'],
            's_content' => $s_content,
            's_remark' => $s_remark,
            's_wx_name' => $s_wx_name
        ];
        if(!$s_com_name || !$s_name || !$s_phone || !$s_inside_name || !$s_inside_phone || !$s_content){
            return json(['status'=>0,'msg'=>'有未填项，请检查']);
        }
        if(mb_strlen($s_content) < 50){
            return json(['status'=>0,'msg'=>'沟通要点字数不能少于50字']);
        }
        //----------------------------手机相关的验证 start -----------------------------------
        if(!preg_match("/^1[23456789]\d{9}$/", $s_inside_phone)){
            return json(['status'=>0,'msg'=>'请填写正确的手机号']);
        }
        if(!preg_match("/^1[23456789]\d{9}$/", $s_phone)){
            return json(['status'=>0,'msg'=>'请填写正确的手机号']);
        }
        if($s_phone == $s_inside_phone){
            return json(['status'=>0,'msg'=>'老师电话不能与客户电话一样']);
        }
        if($s_phone1){
            if(!preg_match("/^1[23456789]\d{9}$/", $s_phone1)){
                return json(['status'=>0,'msg'=>'请填写正确的手机号']);
            }
            if($s_phone1 == $s_inside_phone){
                return json(['status'=>0,'msg'=>'老师电话不能与客户电话一样']);
            }
        }
        if($s_phone2){
            if(!preg_match("/^1[23456789]\d{9}$/", $s_phone2)){
                return json(['status'=>0,'msg'=>'请填写正确的手机号']);
            }
            if($s_phone2 == $s_inside_phone){
                return json(['status'=>0,'msg'=>'老师电话不能与客户电话一样']);
            }
        }
        //手机号有没有人提交
        $have = $this->forPhoneThree($s_phone,$s_phone1,$s_phone2);
        if($have){
            return json(['status'=>0,'msg'=>'此手机号已经有人提交']);
        }
        //----------------------------手机相关的验证 end -----------------------------------
        Db::table('up_shop_copy')
            ->where('s_u_userid',$userInfo['user_id'])
            ->delete();
        $res = Db::table('up_shop_copy')
            ->insertGetId($insert);
        if($res){
            return json(['status'=>200,'msg'=>'ok']);
        }else{
            return json(['status'=>0,'msg'=>'记录失败，请刷新重试']);
        }
    }

    /**
     * 判断手机号有没有被注册过
     * @param $s_phone
     * @param $s_phone1
     * @param $s_phone2
     * @return bool
     */
    public function forPhoneThree($s_phone,$s_phone1,$s_phone2)
    {
        $have = Db::table('up_shop')
            ->where('s_verify','in','1,2')
            ->where('s_status','in','1,2')
            ->where('s_phone|s_phone1|s_phone2',$s_phone)
            ->find();
        if($have){
            return true;
        }
        if($s_phone1){
            $have = Db::table('up_shop')
                ->where('s_verify','in','1,2')
                ->where('s_status','in','1,2')
                ->where('s_phone|s_phone1|s_phone2',$s_phone1)
                ->find();
            if($have){
                return true;
            }
        }
        if($s_phone2){
            $have = Db::table('up_shop')
                ->where('s_verify','in','1,2')
                ->where('s_status','in','1,2')
                ->where('s_phone|s_phone1|s_phone2',$s_phone2)
                ->find();
            if($have){
                return true;
            }
        }
        return false;
    }
    /**
     * 报备第二步
     */
    public function lastStep()
    {
        extract(input());
        $userInfo = Db::table('up_u_user')->where('user_id',session('user_id'))->find();
        $config = Db::table('up_shop_config')->where('id',1)->find();
        if(!$addressDetail || !$lonlat || !$areaid){
            return json(['status'=>0,'msg'=>'地址和经纬度信息不能为空！']);
        }
        $area = explode('-',$areaid);
        $lalo = explode(',',$lonlat);
        //----------------------------------------区域保护 start -------------------------------------------------
        $lat = $lalo[0];
        $lon = $lalo[1];
        $mile = $config['miles'];
        $miles = (int)$mile;
        $field = 's_id,s_com_name';
        $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - s_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(s_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - s_lon * PI() / 180) / 2),2))) * 1000) AS distance';
        $alredy_join = Db::table('up_shop')
            ->where('s_status',2)
            ->where('s_protect',1)
            ->having("distance <= $miles")
            ->field($field)
            ->find();
        if($alredy_join){
            return json(['status'=>0,'msg'=>'保护范围内已经有加盟的商家了！']);
        }
        //----------------------------------------区域保护  end --------------------------------------------------
        $insert = [
            's_area_str' => $address ,
            's_address' => $addressDetail ,
            's_sheng' => $area[0] ,
            's_shi' => $area[1] ,
            's_qu' => $area[2] ,
            's_lon' => $lalo[1] ,
            's_lat' => $lalo[0]
        ];
        $one = Db::table('up_shop_copy')->where('s_u_userid',$userInfo['user_id'])->find();
        if(!$one){
            return json(['status'=>119,'msg'=>'数据出错，请重新填写！']);
        }
        //---------------------------------------------------------------
        $son = [
            'si_u_name' => $userInfo['user_username'],
            'si_u_phone' => $userInfo['user_phone'],
            'si_u_userid' => $one['s_u_userid'],
            'si_name' => $one['s_name'],
            'si_phone' => $one['s_phone'],
            'si_wechat' => $one['s_wx_name'],
            'si_content' => $one['s_content'],
            'si_remark' => $one['s_remark'],
            'si_images' => $upload,
            'si_days' => $one['s_days'],
            'si_time' => date('Y-m-d H:i:s'),
            'si_update_time' => date('Y-m-d H:i:s')
        ];
        //---------------------------------------------------------------
        $newinert = array_merge($insert,$one);
        unset($newinert['s_content']);
        unset($newinert['s_remark']);
        unset($newinert['s_wx_name']);
        unset($newinert['s_id']);
        Db::startTrans();
        try{
            //手机号有没有人提交
            $have = $this->forPhoneShop($one['s_phone'],$one['s_phone1'],$one['s_phone2']);
            if($have){
                $son['si_s_id'] = $have;
                Db::table('up_shop')->where('s_id',$have)->update($newinert);
            }else{
                $sid = Db::table('up_shop')->insertGetId($newinert);
                $son['si_s_id'] = $sid;
            }
            Db::table('up_shop_image')->insertGetId($son);
            Db::table('up_shop_copy')->where('s_u_userid',$userInfo['user_id'])->delete();
            Db::commit();
            return json(['status'=>200,'msg'=>'ok']);
        }catch (\Exception $e) {
            Db::rollback();
            return json(['status'=>0,'msg'=>'记录失败，请刷新重试']);
        }
    }

    public function forPhoneShop($s_phone,$s_phone1,$s_phone2)
    {
        $have = Db::table('up_shop')
            ->where('s_verify|s_status','>=',3)
            ->where('s_phone|s_phone1|s_phone2',$s_phone)
            ->find();
        if($have){
            return $have['s_id'];
        }
        if($s_phone1){
            $have = Db::table('up_shop')
                ->where('s_verify|s_status','>=',3)
                ->where('s_phone|s_phone1|s_phone2',$s_phone1)
                ->find();
            if($have){
                return $have['s_id'];
            }
        }
        if($s_phone2){
            $have = Db::table('up_shop')
                ->where('s_verify|s_status','>=',3)
                ->where('s_phone|s_phone1|s_phone2',$s_phone2)
                ->find();
            if($have){
                return $have['s_id'];
            }
        }
        return false;
    }

    /**
     * 选择地址
     */
    public function goAddress()
    {
        return $this->fetch('addshop/address');
    }















    /**
     * 报备
     */
    public function index1()
    {
        $userInfo = Db::table('up_u_user')->where('user_id', session('user_id'))->find();
        $oldData = Db::table('up_shop_copy')
            ->where('s_u_userid', $userInfo['user_id'])
            ->find();
        $this->assign('oldData',$oldData);
        return $this->fetch();
    }
    /**
     * 报备第一步
     */
    public function firstStep1()
    {
        extract(input());
        $userInfo = Db::table('up_u_user')->where('user_id',session('user_id'))->find();
        $config = Db::table('up_shop_config')->where('id',1)->find();
        $insert = [
            's_u_name' => $userInfo['user_username'],
            's_u_phone' => $userInfo['user_phone'],
            's_u_userid' => $userInfo['user_id'],
            's_com_name' => $s_com_name,
            's_name' => $s_name,
            's_phone' => $s_phone,
            's_phone1' => $s_phone1,
            's_phone2' => $s_phone2,
            's_time' => date('Y-m-d H:i:s'),
            's_endtime' => date('Y-m-d H:i:s',time()+(3600*24*20)),
            's_update_time' => date('Y-m-d H:i:s'),
            's_verify' => 1,
            's_status' => 1,
            's_inside_name' => $s_inside_name,
            's_inside_phone' => $s_inside_phone,
            's_days' => $config['default'],
            's_content' => $s_content,
            's_remark' => $s_remark,
            's_wx_name' => $s_wx_name,
        ];
        if(!$s_com_name || !$s_name || !$s_phone || !$s_inside_name || !$s_inside_phone || !$s_content){
            return json(['status'=>0,'msg'=>'有未填项，请检查']);
        }
        if(mb_strlen($s_content) < 50){
            return json(['status'=>0,'msg'=>'沟通要点字数不能少于50字']);
        }
        //----------------------------手机相关的验证 start -----------------------------------
        if(!preg_match("/^1[23456789]\d{9}$/", $s_inside_phone)){
            return json(['status'=>0,'msg'=>'请填写正确的手机号']);
        }
        if(!preg_match("/^1[23456789]\d{9}$/", $s_phone)){
            return json(['status'=>0,'msg'=>'请填写正确的手机号']);
        }
        if($s_phone == $s_inside_phone){
            return json(['status'=>0,'msg'=>'老师电话不能与客户电话一样']);
        }
        if($s_phone1){
            if(!preg_match("/^1[23456789]\d{9}$/", $s_phone1)){
                return json(['status'=>0,'msg'=>'请填写正确的手机号']);
            }
            if($s_phone1 == $s_inside_phone){
                return json(['status'=>0,'msg'=>'老师电话不能与客户电话一样']);
            }
        }
        if($s_phone2){
            if(!preg_match("/^1[23456789]\d{9}$/", $s_phone2)){
                return json(['status'=>0,'msg'=>'请填写正确的手机号']);
            }
            if($s_phone2 == $s_inside_phone){
                return json(['status'=>0,'msg'=>'老师电话不能与客户电话一样']);
            }
        }
        //手机号有没有人提交
        $have = $this->forPhoneThree($s_phone,$s_phone1,$s_phone2);
        if($have){
            return json(['status'=>0,'msg'=>'此手机号已经有人提交']);
        }
        //----------------------------手机相关的验证 end -----------------------------------
        Db::table('up_shop_copy')
            ->where('s_u_userid',$userInfo['user_id'])
            ->delete();
        $res = Db::table('up_shop_copy')
            ->insertGetId($insert);
        if($res){
            return json(['status'=>200,'msg'=>'ok']);
        }else{
            return json(['status'=>0,'msg'=>'记录失败，请刷新重试']);
        }
    }
    public function forPhoneThree1($s_phone,$s_phone1,$s_phone2)
    {
        $have = Db::table('up_shop')
            ->where('s_verify','in','1,2')
            ->where('s_status','in','1,2')
            ->where('s_phone|s_phone1|s_phone2',$s_phone)
            ->find();
        if($have){
            return true;
        }
        if($s_phone1){
            $have = Db::table('up_shop')
                ->where('s_verify','in','1,2')
                ->where('s_status','in','1,2')
                ->where('s_phone|s_phone1|s_phone2',$s_phone1)
                ->find();
            if($have){
                return true;
            }
        }
        if($s_phone2){
            $have = Db::table('up_shop')
                ->where('s_verify','in','1,2')
                ->where('s_status','in','1,2')
                ->where('s_phone|s_phone1|s_phone2',$s_phone2)
                ->find();
            if($have){
                return true;
            }
        }
        return false;
    }
    /**
     * 报备第二步
     */
    public function lastStep1()
    {
        extract(input());
        $userInfo = Db::table('up_u_user')->where('user_id',session('user_id'))->find();
        $config = Db::table('up_shop_config')->where('id',1)->find();
        if(!$addressDetail || !$lonlat || !$areaid){
            return json(['status'=>0,'msg'=>'地址和经纬度信息不能为空！']);
        }
        $area = explode('-',$areaid);
        $lalo = explode(',',$lonlat);
        //----------------------------------------区域保护 start -------------------------------------------------
        $lat = $lalo[0];
        $lon = $lalo[1];
        $mile = $config['miles'];
        $miles = (int)$mile;
        $field = 's_id,s_com_name';
        $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - s_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(s_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - s_lon * PI() / 180) / 2),2))) * 1000) AS distance';
        $alredy_join = Db::table('up_shop')
            ->where('s_status',2)
            ->where('s_protect',1)
            ->having("distance <= $miles")
            ->field($field)
            ->find();
        if($alredy_join){
            return json(['status'=>0,'msg'=>'保护范围内已经有加盟的商家了！']);
        }
        //----------------------------------------区域保护  end --------------------------------------------------
        $insert = [
            's_area_str' => $address ,
            's_address' => $addressDetail ,
            's_sheng' => $area[0] ,
            's_shi' => $area[1] ,
            's_qu' => $area[2] ,
            's_lon' => $lalo[1] ,
            's_lat' => $lalo[0]
        ];
        $one = Db::table('up_shop_copy')->where('s_u_userid',$userInfo['user_id'])->find();
        if(!$one){
            return json(['status'=>119,'msg'=>'数据出错，请重新填写！']);
        }
        //---------------------------------------------------------------
        $son = [
            'si_u_name' => $userInfo['user_username'],
            'si_u_phone' => $userInfo['user_phone'],
            'si_u_userid' => $one['s_u_userid'],
            'si_name' => $one['s_name'],
            'si_phone' => $one['s_phone'],
            'si_wechat' => $one['s_wx_name'],
            'si_content' => $one['s_content'],
            'si_remark' => $one['s_remark'],
            'si_images' => $upload,
            'si_days' => $one['s_days'],
            'si_time' => date('Y-m-d H:i:s'),
            'si_update_time' => date('Y-m-d H:i:s')
        ];
        //---------------------------------------------------------------
        $newinert = array_merge($insert,$one);
        unset($newinert['s_content']);
        unset($newinert['s_remark']);
        unset($newinert['s_wx_name']);
        unset($newinert['s_id']);
        Db::startTrans();
        try{
            //手机号有没有人提交
            $have = $this->forPhoneShop($one['s_phone'],$one['s_phone1'],$one['s_phone2']);
            if($have){
                $son['si_s_id'] = $have;
                Db::table('up_shop')->where('s_id',$have)->update($newinert);
            }else{
                $sid = Db::table('up_shop')->insertGetId($newinert);
                $son['si_s_id'] = $sid;
            }
            Db::table('up_shop_image')->insertGetId($son);
            Db::table('up_shop_copy')->where('s_u_userid',$userInfo['user_id'])->delete();
            Db::commit();
            return json(['status'=>200,'msg'=>'ok']);
        }catch (\Exception $e) {
            Db::rollback();
            return json(['status'=>0,'msg'=>'记录失败，请刷新重试']);
        }
    }

    public function forPhoneShop1($s_phone,$s_phone1,$s_phone2)
    {
        $have = Db::table('up_shop')
            ->where('s_verify|s_status','>=',3)
            ->where('s_phone|s_phone1|s_phone2',$s_phone)
            ->find();
        if($have){
            return $have['s_id'];
        }
        if($s_phone1){
            $have = Db::table('up_shop')
                ->where('s_verify|s_status','>=',3)
                ->where('s_phone|s_phone1|s_phone2',$s_phone1)
                ->find();
            if($have){
                return $have['s_id'];
            }
        }
        if($s_phone2){
            $have = Db::table('up_shop')
                ->where('s_verify|s_status','>=',3)
                ->where('s_phone|s_phone1|s_phone2',$s_phone2)
                ->find();
            if($have){
                return $have['s_id'];
            }
        }
        return false;
    }

    /**
     * 选择地址
     */
    public function goAddress1()
    {
        return $this->fetch('addshop/address');
    }
}